package com.kalua.list.harvester;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.kalua.list.domainmodel.TextIdentifier;

public class Start {

	private static final Logger logger = LoggerFactory.getLogger(Start.class);	
	
	private static final int ERROR_RETURN_CODE = 1;
	
	private static final String SPRING_CTX_NAME = "harvester-ctx.xml";
	private static final String RETAILER_ID_PARAM_NAME = "retailer";
	
	public static void main(String[] args) {
		String retailerId = null;
		try (ClassPathXmlApplicationContext context = 
				new ClassPathXmlApplicationContext(SPRING_CTX_NAME)) {
			CommandLine commandLine = parseAndValidateArgs(args);
			if (commandLine!=null) {
				retailerId = 
						commandLine.getOptionValue(RETAILER_ID_PARAM_NAME);				
				WebCrawler webCrawler = context.getBean("webCrawler", WebCrawler.class);
				webCrawler.doCrawl(new TextIdentifier(retailerId));				
			}
		} catch (InterruptedException exce) {
			logger.error("Web crawl for {} bailed out with interrupted exception.", retailerId, exce);
		} 
	}
	
	private static CommandLine parseAndValidateArgs(String[] args) {
		CommandLine result;
		
		Options commandLineOptions = buildOptions();
		try {			
			CommandLineParser parser = new GnuParser();			
			result = parser.parse(commandLineOptions, args);
			
			if (!result.hasOption(RETAILER_ID_PARAM_NAME)) {
				printUsage(commandLineOptions);
				System.exit(ERROR_RETURN_CODE);
			}
		} catch (ParseException parseException) {
			logger.error("Unable to parse command line arguments.", 
								parseException);
			printUsage(commandLineOptions);
			result = null;
		}		
		return result;
	}
	
	private static final Options buildOptions() {
		Options result = new Options();		
		result = 
		result	.addOption(
					new Option(	RETAILER_ID_PARAM_NAME,
										true,
										"retailer id/code."));		
		return result;
	}
		 
	private static void printUsage(Options options) {
		HelpFormatter helpFormatter = new HelpFormatter();
		helpFormatter.printHelp(
				"<java> com.kalua.list.harvester.Start", 
				options);
	}
}